package com.cashmama.market.api.domain.oss;

import com.cashmama.market.api.infras.config.ApolloConfigUtil;
import com.fqgj.base.services.oss.OSSService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Component;

import java.io.InputStream;

@Component
@EnableRetry //重试机制开关
public class RetryOSSService {

    @Autowired
    private OSSService ossService;
    @Autowired
    private ApolloConfigUtil apolloConfigUtil;

    @Retryable(value = {Exception.class}, maxAttempts = 3)
    public String uploadFileWithRetry(String fileName, String content) {
        return apolloConfigUtil.getQsyqBaseUrl() + ossService.uploadFile(fileName, content);
    }

    @Retryable(value = {Exception.class}, maxAttempts = 3)
    public String getFileContent(String filePath) {
        String baseUrl = apolloConfigUtil.getQsyqBaseUrl();
        if (StringUtils.isNoneBlank(filePath) && filePath.contains(baseUrl)) {
            filePath = filePath.replace(baseUrl, "");
        }
        return ossService.getFileContent(apolloConfigUtil.getBucketName(), filePath);
    }

    @Retryable(value = {Exception.class}, maxAttempts = 3)
    public String uploadFileWithRetry(String bucketName, InputStream inputStream, long contentLength, String fileName) {
        ossService.uploadFile(bucketName, inputStream, contentLength, fileName);
        return apolloConfigUtil.getQsyqBaseUrl() + fileName;
    }

}
